import dbx;
import webx;
import stdx;
import json;
import time;
import base64;
import imgkit;
from PIL import Image;
from pyc.toolkit import getwebinfo;

def getimagedata(app, url, size = None):
	res = webx.GetHttpResult(url);
	if url.rfind('.ico') + 4 == len(url): imme = webx.GetMimeType('ico');
	else: imme = res.getheader('Content-Type');
	return imme + ':' + base64.b64encode(res.read()).decode();

def main(app):
	res = {'code': stdx.XG_FAIL};
	flag = app.getParameter('flag');
	user = app.getSessionList(('USER', 'DBID'));
	if isinstance(user, int): res['code'] = user;
	elif len(user[0]) <= 0: res['code'] = stdx.XG_TIMEOUT;
	else:
		hdr = user[0] + '.WEBPAGE';
		res['code'] = stdx.XG_OK;
		try:
			with app.dbconnect(user[1]) as db:
				if flag == 'A' or flag == 'U':
					url = app.getParameter('url');
					title = app.getParameter('title');
					folder = app.getParameter('folder');
					if not stdx.CheckLength(title, (1, 32)): res['code'] = stdx.XG_PARAMERR;
					if not stdx.CheckLength(folder, (1, 32)): res['code'] = stdx.XG_PARAMERR;
					elif not stdx.CheckLength(url, (4, 1024)): res['code'] = stdx.XG_PARAMERR;
					try:
						web = json.loads(getwebinfo.main(app));
						if 'icon' in web: image = getimagedata(app, web['icon'], (24, 24));
						else: image = '/res/img/menu/explorer.png';
					except BaseException as e:
						app.trace('IMP', 'grasp url[%s] failed[%s]' % (url, str(e)));
						image = '/res/img/menu/explorer.png';
					if url[0:2] == '//': url = 'http:' + url;
					elif url.lower().find('http://') < 0 and url.lower().find('https://') < 0: url = 'http://' + url.strip('/');
					if flag == 'A':
						sz = db.queryArray('SELECT COUNT(1) AS CNT FROM T_XG_PARAM WHERE ID LIKE ?', hdr + '%');
						if int(sz[0]['cnt']) > 99: res['code'] = stdx.XG_AUTHFAIL;
						else:
							idx = 10;
							while idx > 0:
								id = str(int(time.time() * 10));
								try:
									db.execute('INSERT INTO T_XG_PARAM(ID,NAME,FILTER,PARAM,REMARK,STATETIME) VALUES(?,?,?,?,?,?)', (hdr + id, title, folder, url, image, db.time()));
									db.commit();
									break;
								except BaseException as e:
									stdx.sleep(0.1);
									idx = idx - 1;
									if idx == 0:
										raise e;
					else:
						id = app.getParameter('id');
						if not stdx.CheckLength(id, (1, 32)): res['code'] = stdx.XG_PARAMERR;
						db.execute('UPDATE T_XG_PARAM SET NAME=?,FILTER=?,PARAM=?,REMARK=?,STATETIME=? WHERE ID=?', (title, folder, url, image, db.time(), hdr + id));
						db.commit();
				elif flag == 'D':
					id = app.getParameter('id');
					if not stdx.CheckLength(id, (1, 32)): res['code'] = stdx.XG_PARAMERR;
					db.execute('DELETE FROM T_XG_PARAM WHERE ID=?', hdr + id);
					db.commit();
				else: res['code'] = stdx.XG_PARAMERR;
		except BaseException as e:
			app.trace('ERR', 'system error[%s]' % str(e));
			if str(e).upper().find('DUPLICATE') >= 0: res['code'] = stdx.XG_DUPLICATE;
			else: res['code'] = stdx.XG_SYSERR;
	return stdx.json(res);